//
//  BookcaseCellView.m
//  ebook
//
//  Created by 吴超飞 on 16/3/4.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "BookcaseCellView.h"
#import "DownloadManager.h"

#define angle2Radian(angle)   ((angle) / 180.0 * M_PI)
#define hasUpdate @"● 有更新"

@implementation BookcaseCellView

-(instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    self.backgroundColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewBg_Color");
    
    if (self) {
        
        UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(-3, -3, ImageWidth+6, ImageHeight+6)];
        _bgView = backgroundView;
        backgroundView.userInteractionEnabled = YES;
//        backgroundView.image = [UIImage imageNamed:@"bookcellBackground"];
        [self addSubview:backgroundView];
        [self sendSubviewToBack:backgroundView];
        
        self.coverImageview = [[UIImageView alloc] initWithFrame:CGRectMake(3, 3, ImageWidth, ImageHeight)];
        [_bgView addSubview:_coverImageview];
        
        //下载加载进度
        self.progressView = [[DAProgressOverlayView alloc] initWithFrame:self.coverImageview.bounds];
        [self.coverImageview addSubview:self.progressView];
        self.progressView.hidden = YES;
        //推荐显示
        UIImage *reImage = [UIImage imageNamed:@"bookcaserecomend"];
        UIImageView *reImageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.coverImageview.frame)-reImage.size.width-2, 0, reImage.size.width, reImage.size.height)];
        reImageView.image = reImage;
        //是否是推荐数据
        [self.coverImageview addSubview:reImageView];
        _reImageView = reImageView;
        reImageView.hidden = YES;
        
        //书名
        _booknameLabel = [[UILabel alloc] initWithFrame:CGRectMake(-1, CGRectGetMaxY(_coverImageview.frame)+5, ImageWidth+2, 17)];
        _booknameLabel.font = [UIFont systemFontOfSize:13];
        _booknameLabel.backgroundColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewNameBg_Color");
        _booknameLabel.textAlignment = NSTextAlignmentLeft;
        
        _booknameLabel.textColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewNameText_Color");
        _booknameLabel.numberOfLines = 1;
        _booknameLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        [self addSubview:_booknameLabel];
        
        _foreBgview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ImageWidth, ImageHeight)];
        _foreBgview.backgroundColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewCorverBg_Color");
        _foreBgview.hidden = YES;
        [self addSubview:_foreBgview];
        
        float space = 1.5f;
        NSString *testStr = [hasUpdate stringByAppendingString:@" 已读100.0%"];
        UIFont *statusFont = [UIFont systemFontOfSize:[self fitFontSize:CGSizeMake(ImageWidth-space, 20) ofText:testStr]];
        
        //book status
        UILabel *bookStatusLabel = [[UILabel alloc] init];
        bookStatusLabel.textColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewStatusText_Color");
        bookStatusLabel.backgroundColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewStatusBg_Color");
        bookStatusLabel.textAlignment = NSTextAlignmentLeft;
        bookStatusLabel.font = statusFont;
        _bookStatusLabel = bookStatusLabel;
        [self addSubview:bookStatusLabel];
        
        //计算字的宽度
        CGSize statusSize = [hasUpdate sizeWithAttributes:@{NSFontAttributeName:statusFont}];
        bookStatusLabel.frame = CGRectMake(0, CGRectGetMaxY(_booknameLabel.frame), statusSize.width, 20);
        
      //已读％
        UILabel *bookReadedPercentLabel = [[UILabel alloc] initWithFrame:CGRectMake(statusSize.width, CGRectGetMaxY(_booknameLabel.frame), ImageWidth-statusSize.width+1, 20)];
        bookReadedPercentLabel.textColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewReadedStatusText_Color");
        bookReadedPercentLabel.backgroundColor = MTConfigColor(@"MTBookshelf_bookcaseCellViewReadedStatusBg_Color");
        bookReadedPercentLabel.textAlignment = NSTextAlignmentRight;
        bookReadedPercentLabel.font = statusFont;
        [self addSubview:bookReadedPercentLabel];
        _readedPercentLabel = bookReadedPercentLabel;
        
        //添加删除按钮
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteBtn.frame = CGRectMake(self.frame.size.width - 24, 0, 24, 24);
		_deleteBtn.center = _coverImageview.center;
        _deleteBtn.contentMode = UIViewContentModeTopRight;
        
        [_deleteBtn setBackgroundImage:[UIImage imageNamed:@"delete_icon"] forState:UIControlStateNormal];
        [_deleteBtn addTarget:self action:@selector(deleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _deleteBtn.hidden = YES;
        [self addSubview:_deleteBtn];
    }
    
    //长按手势
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPressGestureRecognizer:)];
    [self addGestureRecognizer:longGesture];
    
    //添加点击手势事件
    _tapGestureRecognizer = [[UITapGestureRecognizer  alloc] initWithTarget:self action:@selector(tapOnContentView:)];
    _tapGestureRecognizer.delegate = self;
    [self addGestureRecognizer:_tapGestureRecognizer];
    
    return self;
}

-(void)setBook:(Book *)book{
    if(!book)return;
    _booknameLabel.text = book.bookname;
    [self.coverImageview sd_setImageWithURL:[NSURL URLWithString:book.coverpicurl] placeholderImage:[UIImage imageNamed:@"bookcellBackground"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if(error){
            NSLog(@"封面显示错误：%@",error);
            return ;
        }
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(ImageWidth, ImageHeight), NO, 0.f);
        [image drawInRect:CGRectMake(0.f, 0.f, ImageWidth, ImageHeight)];
        UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        self.coverImageview.contentMode = UIViewContentModeScaleToFill;
        self.coverImageview.image = fullImage;
    }];
    
    //判断是否有更新
    if ([book.lasthaptercount intValue]<[book.chaptercount intValue]) {
//        MTLog(@"有更新:bookname:%@,lastcount:%@,newcount:%@",book.bookname,book.lasthaptercount,book.chaptercount);
        _bookStatusLabel.text = hasUpdate;
        _bookStatusLabel.textColor = [UIColor redColor];
    }else{
        if ([book.fullflag intValue] == 1) {
            _bookStatusLabel.text = @"完结 ";
        } else {
            _bookStatusLabel.text = @"连载 ";
        }
    }
    
    //是否是推荐数据
    if (book.isrecommend) {
        self.reImageView.hidden = NO;
    }
    
    float totoalCount = [book.chaptercount floatValue];
    float readPercent = totoalCount==0?0:(float)[book.rposition intValue]*100/totoalCount;
    if(readPercent==0)
        readPercent=0.001;
    
    if([[[DownloadManager shareInstance] currentDownload].book.bookid integerValue]==[book.bookid integerValue]){
        _readedPercentLabel.text = @"下载中";
    }else{
        if ([@"0.001" isEqualToString:[NSString stringWithFormat:@"%0.3f", readPercent]]) {
            _readedPercentLabel.text = @"未读";
        } else {
            _readedPercentLabel.text = [NSString stringWithFormat:@"已读%.1f%@", readPercent, @"%"];
        }
    }
    
    [self update:book];
}

-(void)update:(Book*)book{
    
}

-(float)fitFontSize:(CGSize)size ofText:(NSString *)text{
    
    int font = 9;
    while (font<11) {
        CGSize tSize = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}];
        if (tSize.width<size.width&&tSize.height<size.height) {
            font++;
        }else{
            break;
        }
    }
    return font;
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if ([touch.view isKindOfClass:[UIButton class]]) {
        return NO;
    }
    return YES;
}

-(void)setIsCanDelete:(BOOL)isCanDelete{
    
    _isCanDelete = isCanDelete;
    self.deleteBtn.hidden = !_isCanDelete;
    self.foreBgview.hidden = !_isCanDelete;
    
    if (_isCanDelete) {//可删除，抖动动画
        //1.创建核心动画
        CAKeyframeAnimation *keyAnima=[CAKeyframeAnimation animation];
        keyAnima.keyPath=@"transform.rotation";
        //角度转弧度
        //度数 / 180 * M_PI
        keyAnima.values=@[@(-angle2Radian(1)),@(angle2Radian(1)),@(-angle2Radian(1))];
        
        keyAnima.removedOnCompletion=NO;
        keyAnima.fillMode=kCAFillModeForwards;
        keyAnima.duration=0.2;
        
        //设置动画重复的次数
        keyAnima.repeatCount=MAXFLOAT;
        //2.添加核心动画
        [self.layer addAnimation:keyAnima forKey:@"shake"];
    } else {
        [self.layer removeAnimationForKey:@"shake"];
    }
}

- (void)LongPressGestureRecognizer:(UIGestureRecognizer *)gr
{
    if ([self.delegate respondsToSelector:@selector(bookcaseCellView:longPressGestureRecognizer:)])
    {
        [self.delegate bookcaseCellView:self longPressGestureRecognizer:gr];
    }
}

- (void)tapOnContentView:(UITapGestureRecognizer *)tapGestureRecognizer
{
    if (!self.deleteBtn.isHidden) {//正在编辑的时候点击图标时直接触发删除事件
        [self deleteButtonClick:_deleteBtn];
        return;
    }
    
    if ([self.delegate respondsToSelector:@selector(bookcaseCellView:tapedWhileIsEdit:)]) {
        [self.delegate bookcaseCellView:self tapedWhileIsEdit:!self.deleteBtn.isHidden];
    }
}

-(void)deleteButtonClick:(UIButton *)btn{
    
    if ([self.delegate respondsToSelector:@selector(bookcaseCellView:deleteBtnClick:)]) {
        [self.delegate bookcaseCellView:self deleteBtnClick:_deleteBtn];
    }
}

- (void)drawRect:(CGRect)rect {
    
}

-(void)dealloc{
    _tapGestureRecognizer.delegate = nil;
    _tapGestureRecognizer = nil;
}

@end
